package grimbo.goodwinfooty.server;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author paul
 * 
 */
public class ByteUtils {
	/**
	 * @param ob
	 * @return
	 * @throws IOException
	 */
	public static byte[] objectToBytes(Object ob) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(ob);
		oos.flush();
		byte[] bytes = baos.toByteArray();
		return bytes;
	}

	/**
	 * @param bytes
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static Object bytesToObject(byte[] bytes) throws IOException,
			ClassNotFoundException {
		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		ObjectInputStream ois = new ObjectInputStream(bais);
		Object ob = ois.readObject();
		return ob;
	}

	/**
	 * @param in
	 * @return
	 * @throws IOException
	 */
	public static byte[] readStream(InputStream in) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		BufferedInputStream bis = (in instanceof BufferedInputStream) ? (BufferedInputStream) in
				: new BufferedInputStream(in);
		int i = bis.read();
		while (i > -1) {
			baos.write(i);
			i = bis.read();
		}
		return baos.toByteArray();
	}
}
